package com.zmh.service.http;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zmh.common.HtmlUtil;
import com.zmh.dao.http.BtshoufaMapper;
import com.zmh.entity.MailEntity;
import com.zmh.service.http.utils.HttpAPIService;
import com.zmh.service.msg.MailService;

/**
 * BT首发论坛刷新
 * @author zhoumh
 * @version 创建时间：2018年7月20日 上午11:08:24 
 * @Description 
 */
@Service
public class BtshoufaHttp {
	private static Logger logger = LoggerFactory.getLogger(BtshoufaHttp.class);
	@Autowired
	private HttpAPIService httpAPIService;
	@Autowired
	private BtshoufaMapper btshoufaMapper;
	@Autowired
	private MailService mailService;
	
	public void getBtshoufa() throws Exception {
		String html = httpAPIService.doGet("http://btshoufa.net/forum-41-1.html");
		Document doc = Jsoup.parse(html);
		Elements elements = doc.select("table#threadlisttableid").select("tbody[id^=normalthread]").select("th.common,th.new").select("a.s");
//		logger.info(doc.select("table#threadlisttableid").select("tbody[id^=normalthread]").select("th.common,th.new").toString());
		String content = "";
		for (Element element : elements) {
			String id = element.attr("href").split("-")[1];
			String name = element.text();
			if (StringUtils.isEmpty(btshoufaMapper.getOne(id))) {
				btshoufaMapper.insert(id, name);
				String url = "http://www.btshoufa.com/"+element.attr("href");
				content = getContent(url);
//				logger.info(content);
				mailService.saveMail(new MailEntity("Btshoufa提醒<zhoumh1985@qq.com>", "zmh1812@qq.com", "Btshoufa更新提醒", content,"sendHtmlMail"));
				
			}
		}
		logger.info("已完成本次btshoufa刷新！");
		
	}
	
	public String getContent(String url) throws Exception{
		String content = "<html></br><body></br>";
		String html = httpAPIService.doGet(url);
		Document doc = Jsoup.parse(html);
		Element td = doc.select("td.t_f").first();
		content = content.concat("<h4>"+doc.select("span#thread_subject").text()+"</br>"+url+"</h4></br>");
		content = content.concat("<p></br>"+HtmlUtil.delHTMLTag(td.toString()))+"</p></br>";
		Elements es = td.select("img.zoom");
		for (Element element : es) {
			//重组剧照图片
			String src = element.attr("src");
			if (StringUtils.isEmpty(src)) {
				src = element.attr("file");
			}
			content = content.concat("<img src='"+src+"'></br>");
		}
//		logger.info(content);
		return content;
	}
}
